More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

The Florist’s Colourful Bouquet Composer – Python Challenge

Welcome to this Python challenge! This time, we are going to help a florist compose beautiful, colourful bouquets for their customers. Your task is to write a Python program that recommends different flowers based on the colours the customer wants and the number of different flowers they would like in their bouquet.

The program should:

  1. Ask the user for the colours they want in their bouquet.
  2. Ask the user for the number of different flowers they want in their bouquet.
  3. Suggest a selection of flowers that match the requested colours and number.

For instance, if the user wants a red, purple and yellow bouquet with 5 different types of flowers, the program might suggest:

  • Red Tulips
  • Red Poppies
  • Purple Wisteria
  • Purple Orchids
  • Yellow Daffodils

Getting Started

To complete this challenge we will use a dictionary data structure. The keys of our dictionary will be the different colours. For each colour, our dictionary will store a list of flowers matching the colour.

Here’s our dictionary data structure called flowers:

flowers = {
    "Red": ["Rose", "Tulip", "Carnation", "Geranium", "Poppy", "Amaryllis", "Anemone", "Camellia"],
    "Purple": ["Lilac", "Orchid", "Lavender", "Allium", "Clematis", "Bellflower", "Iris", "Wisteria"],
    "Yellow": ["Sunflower", "Daffodil", "Marigold", "Dahlia", "Tulip", "Buttercup", "Goldenrod", "Forsythia"],
    "Blue": ["Bluebell", "Cornflower", "Delphinium", "Hydrangea", "Iris", "Periwinkle", "Forget-me-not", "Agapanthus"],
    "White": ["Lily", "Jasmine", "Daisy", "Gardenia", "Baby's Breath", "Magnolia", "Peony", "Snowdrop"],
    "Pink": ["Peony", "Cherry Blossom", "Azalea", "Carnation", "Begonia", "Camellia", "Dahlia", "Foxglove"],
    "Orange": ["Marigold", "Zinnia", "Nasturtium", "Buttercup", "Bird of Paradise", "Calendula", "Geum", "Tiger Lily"],
    "Green": ["Green Rose", "Bells of Ireland", "Green Hydrangea", "Green Zinnia", "Green Carnations", "Green Chrysanthemum"],
    "Black": ["Black Dahlia", "Black Rose", "Black Callas", "Black Pansy", "Black Tulip"],
    "Brown": ["Chocolate Cosmos", "Brown-Eyed Susan", "Cattail", "Brown Orchid"]
}

Python Code

Here’s a basic outline of how your program might look:

     Input: Ask the user for the colours and the number of flowers.
     Process: Use the input to select flowers from your dictionary. Randomly selecting flowers from the list for a given colour will provide more variety in the suggestions made by your program.
     Output: Print the suggested bouquet.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

How tall is Big Ben? (Python Challenge)

In this blog post we will find an easy method to estimate the height of any high building or tree by measuring the length of its shadow in the ground. We will apply this method to estimate the height of Big Ben, London, UK; technically the Elizabeth Tower, Big Ben being the name of the large bell inside this clock tower. This challenge provides a practical application of similar triangles and basic trigonometry, which are fundamental concepts in geometry.

Similar Triangles Method

To estimate the height of a tree or a building using its shadow, we can use the concept of similar triangles. Here’s a simple diagram to illustrate the method:

The two triangles formed by both the Elizabeth Tower and its shadow and by the phone box and its shadow are similar triangles: two triangles are similar if the angles are the same size. As a consequence, the corresponding sides of these triangles are in the same ratio. We can therefore estimate the height of the clock tower using the following formula:

It’s effectively a lot more practical for anyone to measure the length of a shadow on the ground, and to measure the height of a smaller reference object such as a person or a telephone box, than to measure the actual height of a building!

Python Challenge

Your task is to write a Python program that will:

     Take three inputs: l, h, and L: The length of the telephone box shadow (l), the height of the telephone box (h) and the length of the shadow of the Elizabeth Tower (L)
     Use the three input values to work out the height of the Elizabeth Tower (H)
     Output the estimated height of the Elizabeth Tower to one decimal place.

To test your program use the following values:

Can you then use your program to estimate the height of the Eiffel Tower using a 1.85m tall French man as your reference object and the following shadow measurements:

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

DNA Sequence Analysis – Python Challenge

You are a bioinformatics researcher working on analysing DNA sequences. Your task is to write a Python program that can perform various analyses on a given DNA sequence. The program should be able to count nucleotides, find complementary strands, and identify specific patterns within the DNA sequence.

What is DNA?

DNA, or deoxyribonucleic acid, is a molecule that carries the genetic instructions used in the growth, development, functioning, and reproduction of all known living organisms and many viruses. DNA is often referred to as the “blueprint of life” because it contains the information needed to build and maintain an organism.

What is a DNA Sequence Made Of?
A DNA sequence is a chain of nucleotides, which are the basic building blocks of DNA. There are four types of nucleotides bases in DNA with different chemical composition::

  • Adenine (A)
  • Thymine (T)
  • Cytosine (C)
  • Guanine (G)

The sequence of these nitrogenous bases along the DNA strand encodes genetic information. The bases pair specifically: Adenine pairs with Thymine (A-T), and Cytosine pairs with Guanine (C-G). This pairing is crucial for the replication and transcription of DNA.

DNA has a double-helix structure, which means it is made up of two long strands that twist around each other like a spiral staircase. Each strand is composed of a sequence of nucleotides, and the two strands are held together by hydrogen bonds between the paired bases.

What is DNA Sequence Analysis used for?

DNA sequence analysis is a fundamental tool in genetic and biological research. It involves examining the nucleotide sequences of DNA to understand genetic information, identify mutations, and study evolutionary relationships. By comparing DNA sequences, researchers can identify genetic variations that may contribute to diseases, track the spread of pathogens, and even trace the evolutionary history of species. Overall, DNS sequence analysis is vital for uncovering the genetic basis of traits and diseases, thereby driving innovations in healthcare, agriculture, and environmental science.

Python Challenges

Use the tabs below to access 5 Python challenges, all based on using string handling techniques to analyse a DNA sequence.

Task 1: Counting NucleotidesTask 2: Finding the Complementary StrandTask 3: Identifying PatternsTask 4: Transcribing DNA to RNATask 5: Calculating GC Content

Task 1: Counting Nucleotides

Write a function called count_nucleotides() that takes a DNA sequence as a parameter and returns a dictionary with the counts of each nucleotide (A, T, C, G).

Example:

dna_sequence = "ATGCGATCCATGACAAT"
nucleotides = count_nucleotides(dna_sequence)
print(nucleotides)
# Output: {'A': 6, 'T': 4, 'C': 4, 'G': 3}

Task 2: Finding the Complementary Strand

Write a function called complementary_strand() that takes a DNA sequence as a parameter and returns its complementary strand. In DNA, the complementary base pairs are A-T and C-G.

Example:

dna_sequence = "ATGCGATTCA"
complementatry_dna_sequence = complementary_strand(dna_sequence)
print(complementatry_dna_sequence)
# Output: "TACGCTAAGT"

Task 3: Identifying Patterns

Within the DNA sequence we can identify patterns for the different amino acids that makes up the DNA. Each amino acid can be identified using a sequence of 3 nucleotides (called a codon).

From the diagram below we can see that the codons GTA, GTC, GTT and GTG are all valid codons for the Valine amino acid whereas AGC and AGT are the codons for Serine.

Write a function called find_pattern() that takes a DNA sequence and a pattern (e.g. a three-letter codon) as parameters, and returns the starting indices of all occurrences of the pattern in the DNA sequence.

Example:

dna_sequence = "ATAGCGATATCGAGCTAC"
pattern = "AGC"
positions = find_pattern(dna_sequence, pattern)
print(positions)
# Output: [2, 12]

Task 4: Transcribing DNA to RNA

DNA (Deoxyribonucleic Acid) is a double-stranded molecule with a deoxyribose sugar and the nitrogenous bases Adenine (A), Thymine (T), Cytosine (C), and Guanine (G). It stores genetic information long-term and is primarily found in the nucleus of cells. RNA (Ribonucleic Acid), on the other hand, is typically single-stranded, contains a ribose sugar, and uses Uracil (U) instead of Thymine. RNA is involved in the transmission and expression of genetic information, playing roles in protein synthesis and gene regulation. DNA is more stable, making it suitable for long-term storage, while RNA is less stable and more reactive, fitting its dynamic roles in cellular processes.

Write a function called transcribe_DNA_to_RNA() that takes a DNA sequence as a parameter and returns the corresponding RNA sequence. In RNA, thymine (T) is replaced by uracil (U).

Example:

dna_sequence = "ATGCTAGCT"
rna_sequence = transcribe_DNA_to_RNA(dna_sequence))
print(rna_sequence)
# Output: "AUGCUAGCU"

Task 5: Calculating GC Content

Write a function called gc_content() that takes a DNA sequence as a parameter and returns the GC content as a percentage. The GC content is the percentage of nucleotides in the DNA sequence that are either G or C.

Example:

dna_sequence = "ATGCGAT"
gc = gc_content(dna_sequence)
print(gc)
# Output: 57.14 %

Python Code

Complete the code for the 6 functions describes above in the following Python IDE:

Here si the expected output for your code:

Expected Output:

DNA Sequence: ATAGCGATCGTAGTTCATAGCTACGTGCGATAGCTCAA
Count Nucleotides: {'A': 11, 'T': 10, 'C': 8, 'G': 9}
Complementary Strand: TATCGCTAGCATCAAGTATCGATGCACGCTATCGAGTT
Find Pattern 'AGC': [2, 18, 31]
Transcribe DNA to RNA: AUAGCGAUCGUAGUUCAUAGCUACGUGCGAUAGCUCAA
GC Content: 44.73684210526316 %
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

The Archaeologist’s Python Challenge

In this challenge, you will write a Python script to help an archaeologist estimate the age of an artefact using Carbon-14 dating. This method is commonly used in archaeology to find out how old organic materials and can be used on objects as old as 60,000 years. By organic materials we mean anything that originate from living organisms including bone, cloth, wood and plant fibers. Carbon-14 dating works by measuring the amount of Carbon-14, a radioactive isotope of carbon, that remains in the object. When an organism dies, it stops taking in new Carbon-14, and the existing Carbon-14 starts to decay at a known rate. By measuring the remaining Carbon-14, scientists can estimate how long ago the organism died.

Python Challenge

Your task is to write a Python script that calculates the age of an artefact based on its remaining Carbon-14 content. The script will include 3 steps:

Step 1: Input

Take as an input from the end user the current ratio of Carbon-14 to Carbon-12 in the artefact. (Note that as Carbon-12 is stable/does not decay over time, the ratio of Carbon-14 to Carbon-12 is pro-rata to the amount of carbon 14 remaining in the organism).

Step 2: Process
Apply the following Carbon-14 dating formula to estimate the age of the artefact.

Assuming the initial Carbon-14 to Carbon-12 ration is 1×10-12 = 1 ppt (parts per trillion), we can simplify the formula as follows

In the above formula:

  • The Carbon-14 ratio is expressed in parts per trillion (ppt).
  • t1/2 represents the Carbon-14 half-life, in other words the total number of years it takes for half of the radioactive carbon-14 atoms in a sample to decay into nitrogen-14 atoms. The half-life of Carbon-14 is approximately 5,730 years.

Using Python you can calculate a natural logarithm (ln) using math.log() from the math library:

import math
ln2 = math.log(2)
print("ln(2) = " + str(ln2))

Step 3: Output
Output the estimated age (in years) of the artefact.


After implementing your script using the online Python IDE below, you will use your script to estimate the age of the following 3 artefacts:

  • The Bakhshali manuscript (Carbon-14 Ratio: 0.878 ppt)
  • Tutankhamun’s tomb (Carbon-14 Ratio: 0.695 ppt)
  • The Sutton Hoo Anglo-Saxon Helmet (Carbon-14 Ratio: 0.844 ppt)

The Bakhshali Manuscript

The Bakhshali manuscript is an ancient Indian mathematical text written on birch bark that was found in 1881 in the village of Bakhshali, Mardan (near Peshawar in present-day Pakistan)

The carbon-14 ratio of the Bakhshali manuscript is 0.878 ppt.

The most recent Carbon dating tests from Oxford University revealed that the Bakshali manuscript dates from 799 – 1102 AD (9th – 11th century).

This means the manuscript would be between approximatively 900 to 1200 years old. Is this what your Python script is estimating?

Tutankhamun’s Tomb

Archaeologists have been able to use the Carbon-14 method to estimate the age of a few seeds found in the tomb of the Egyptian Pharaoh Tutankhamun who ruled over Ancient Egypt many thousands of years ago.

The carbon-14 ratio of the seeds: 0.695 ppt

Note that samples from Tutankhamun’s tomb were dated using radiocarbon dating techniques, with some samples dating to around 846 BC and 899 BC. These dates are significantly earlier than the traditionally accepted dates for Tutankhamun’s reign, which is generally placed around 1332–1323 BC.

This would mean that the seeds are approximatively 3,000 years old. Is this what your Python script is estimating?

The Sutton Hoo Anglo-Saxon Helmet

The Sutton Hoo helmet, discovered in an Anglo-Saxon ship burial at Sutton Hoo, Suffolk, UK, It is estimated to be around 1,400 years old, dating from the early 7th century (circa 620-625 AD). It was buried in a ship, along with many other artifacts, as part of an elaborate burial ritual. It is widely associated with Anglo-Saxon leader King Rædwald of East Anglia.

The carbon-14 ratio of wooden artefacts found next to the helmet: 0.844 ppt

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

The K2-18b Exoplanet – Space Exploration Mission

In an exciting leap forward for space science, the James Webb Space Telescope recently discovered the exoplanet K2-18b, a world located in the habitable zone of its red dwarf star. With conditions that suggest it might support life, K2-18b has captured the attention of astronomers and astrobiologists alike. The planet’s potential to harbour life is a monumental discovery, opening new possibilities in the search for extra-terrestrial organisms and, perhaps, even life beyond Earth.

The Mission

To achieve this ambitious goal, we are launching a pioneering mission to send a probe to K2-18b using a newly discovered technology called “light year tele-transportation.” This ground-breaking method will enable us to traverse the vast expanse of space in a fraction of the time it would take with traditional propulsion systems.

Once the probe reaches K2-18b, it will deploy a rover equipped with an array of advanced instruments. The rover’s primary objectives are to explore the planet’s surface, collect atmospheric weather data, and create detailed 3D scans of the environment. To accomplish these tasks, the rover is preloaded with a library of functions that can be used to pre-program missions. These missions will be loaded onto the rover, which will then complete them autonomously.

The Challenge

Each mission algorithm is designed to perform a specific task, such as navigating to a waypoint, collecting atmospheric data, or creating a 3D scan of a particular area.

The rover has a limited power supply and data storage capacity, so it is crucial that we optimise its operations to ensure it can complete its missions without running out of power or exceeding its data storage limits.

Your task is to test 10 of the pre-coded mission algorithms to predict the power consumption and data usage of each mission. By doing so, you will help us ensure that the rover can operate efficiently and effectively on K2-18b.

You can access the 10 mission algorithms in the below frame. By testing these algorithms, you will play a crucial role in ensuring the success of our mission to explore this distant world. We count on you to check all 10 algorithms rigorously!
The K2-18b Exoplanet – Space Exploration MissionOpen in New Window

Tagged with:

The Marine Biologist’s Python Challenge

For this challenge we will write a program that would be useful for a team of marine biologists working on a conservation project along the coast. Their aim is to estimate the population of sea turtles living in a particular bay. Since it’s impossible to count every single turtle in the water, the biologists use a clever technique known as the capture-recapture method.

Your challenge is to create a Python program that helps our team of marine biologists estimate the total sea turtles population based on data collected during two observation trips.

What Is the Capture-Recapture Method?

The capture-recapture method is commonly used by wildlife researchers to estimate animal populations without counting every individual.

Here’s how it works:

  1. First Capture: A group of animals is captured, marked (e.g. tagged), and released.
  2. Second Capture: Later, another group is captured, and researchers count how many are already marked.
  3. Using the overlap between the two groups (the number of animals marked within the second capture), we can estimate the total population with the following formula:

So let’s use the following example to better understand how this formula works:
During their first trip, the marine biologists catch and tag 80 sea turtles before releasing them.
On a second trip a few weeks later, they catch 110 sea turtles, 25 of which are already tagged.

Using this information, we can apply the capture-recapture formula to estimate the total population of sea-turtles living in the bay:

Python Challenge

Your task is to write a Python program that:

    Asks the user to input:

      The number of turtles tagged in the first capture.
      The number of turtles caught in the second capture.
      The number of recaptured tagged turtles in the second sample.

    Applies the capture-recapture formula.
    Outputs the estimated total population of sea turtles.

Python Code

Ready to dive in? Start coding and help the marine biologists make a difference!

Testing

Once your code is done, complete the following tests to check that your code is working as it should:

Test # Input Values Expected Output Actual Output
#1 First Capture: 80
Second Capture: 110
Recaptures: 25
Estimated Population Size: 352
#2 First Capture: 90
Second Capture: 70
Recaptures: 12
Estimated Population Size: 525
#3 First Capture: 70
Second Capture: 50
Recaptures: 0
We cannot estimate the population size with this data (0 recaptures)

Why It Matters

The capture-recapture approach is widely used by marine biologists, ecologists, and conservationists to study animal populations in a humane and efficient way. By writing a Python program for this method, you’re not only learning about real-world data science, but also supporting work that protects endangered species!

Extra Challenge

The team of marine biologists would like to improve the accuracy of their sea turtles population size estimate. To do so, they have decided to conduct this capture/recapture experiment six times, once every week over a period of 6 weeks. They have recorded their data in a file called Sea-Turtles.csv as follows:

first capture,second capture,number of retakes
80,110,25
76,70,16
90,70,19
98,64,18
82,72,18
85,78,20

We have saved this csv file as a separate tab in the Python IDE below.

The following Python code can be used to read our CSV file line by lineand extract the data from each line:

file = open("Sea-Turtles.csv","r")

for line in file:
   data = line.split(",")
   firstCapture = int(data[0])  
   secondCapture = int(data[1])
   retakes = int(data[2])
   print("First Capture: " + str(firstCapture) + " - Second Capture: " + str(secondCapture) + " - Retakes: " + str(Retakes))
  
file.close()

Your task is to tweak the following code to calculate the estimated population size for each experiment and work out the average population size over these 6 experiments.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Stock Level Checker Program – Python Challenge

With this Python challenge, we’re going to focus on using file handling techniques to create a simple yet practical program to be used by a shop assistant to quickly check their stock levels. The goal is to write a Python script that allows users to check the availability of clothing items in stock. The program will prompt the user to select a piece of clothing, a size, and a colour, and then it will check a CSV file to see if the item is available.

CSV File?

To begin, we will need a CSV file that contains the stock information. CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a comma “,”. Sometimes we use other symbols instead of the comma such as a semi-colon “;” or a pipe “|”. Below is an example of what the CSV file might look like:

item,size,color,quantity
t-shirt,S,red,5
t-shirt,M,blue,3
t-shirt,L,red,2
t-shirt,M,red,0
t-shirt,S,blue,0
t-shirt,S,green,1
shorts,M,blue,1
shorts,L,green,0
shorts,S,green,2
shorts,S,blue,3
cap,L,red,4
cap,M,white,2
cap,M,black,0
cap,S,red,5

We have saved this data into a CSV file called stock.csv available as a separate tab in the Python IDE below.

The following Python code can be used to read our CSV file line by line and extract the data from each line:

file = open("stock.csv","r")

for line in file:
   data = line.split(",")
   item = data[0]  
   size = data[1]
   colour = data[2]
   stockLevel = int(data[3])
   print(item + " - " + size + " - " + colour + " - Quantity in Stock: " + str(stockLevel))
  
file.close()

Python Code

Your task is to complete the code provided below to perform the following tasks:
Your task is to create a Python program that performs the following steps:

    Prompt the user to enter a piece of clothing (e.g. t-shirt, shorts, cap).
    Ask the user to select a size (e.g. S, M, L).
    Request the user to choose a colour (e.g. red, blue, green, white, black).
    Check a CSV file to see if the item is in stock.
    Display a message indicating whether the item is available or out of stock.

Note that an item is out of stock if its stock level is zero or if it is not listed in the CSV file.

Testing

Once your code is done, complete the following tests to check that your code is working as it should:

Test # Input Values Expected Output Actual Output
#1 Item: T-Shirt
Size: L
Colour: Red
This item is in stock (Stock Level: 2)
#2 Item: Cap
Size: M
Colour: Black
This item is out of stock
#3 Item: Shorts
Size: S
Colour: Blue
This item is in stock (Stock Level: 3)
#4 Item: Cap
Size: L
Colour: White
This item is out of stock

Next step…

This challenge is a great way to practise file handling in Python. By completing this task, you’ll gain experience in reading from CSV files and processing user input. Feel free to expand the program by adding more features, such as updating the stock quantity or allowing users to add new items to the stock. You may also make your program more robust by validating user inputs and converting the case to match the case used in the CSV file. (e.g. size automatically converted to uppercase and colour automatically converted to lowercase).

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

Ada Lovelace and the First Computer Algorithm

In this post we will focus on a very specific algorithm called the Note G algorithm, written in 1843 by Ada Lovelace. Born in 1815, Ada Lovelace is celebrated as a visionary whose work laid the groundwork for modern computing. Among her most notable contributions is the Note-G algorithm, widely regarded as the first computer algorithm, even though the machine it was designed for—the Analytical Engine—was never built.

The Analytical Engine: A Vision Ahead of Its Time

The Analytical Engine was a mechanical general-purpose computer proposed by Charles Babbage. Although it remained a theoretical construct, the engine’s design was revolutionary. It was intended to perform complex calculations and could be programmed using punched cards, a concept that would later influence the development of early computers.

The Note-G Algorithm: The First of Its Kind

Ada Lovelace’s Note-G algorithm was designed to be implemented on the Analytical Engine. The algorithm was part of her translation and expansion of an Italian article on the engine, where she detailed how the machine could compute Bernoulli numbers. This work is significant because it represents the first explicit description of a step-by-step process for a machine to perform a complex calculation—the essence of what we now call an algorithm.

Diagram of an algorithm for the Analytical Engine for the computation of Bernoulli numbers, from Sketch of The Analytical Engine Invented by Charles Babbage by Luigi Menabrea with notes by Ada Lovelace

Bernoulli Numbers?

For those unfamiliar with the term, Bernoulli numbers are a sequence of rational numbers with deep connections to number theory. They appear in various areas of mathematics, including the expansion of trigonometric functions and the calculation of sums of powers of integers. The sequence starts with B₀ = 1, B₁ = -1/2, B₂ = 1/6, and so on, with each number defined by a specific recursive formula.

Lovelace’s algorithm to compute these numbers was ground breaking because it demonstrated that a machine could perform tasks that went beyond simple arithmetic, showcasing the potential for automated computation.

Testing the Note-G Algorithm

Let’s use our Analytical Engine emulator to test Ada Lovelace’s algorithm. The algorithm provided below is a direct translation of Ada Lovelace’s algorithm (See picture above). It is used to calculate Bernoulli Number 7( B7).

To work out the value of B7, the algorithms relies on the values of B1, B3 and B5.

Bj Fraction Decimal
B1 1/6 +0.166666666
B3 −1/30 −0.033333333
B5 1/42 +0.023809523

As the Store of the analytical engine can only store integer values (whole numbers with no decimal), we are shifting the values being calculated by 12 digits.

For instance the output of our program should be read as follows: B7 = -33333333336 x 10-12 = 0.033333333336 ≈ -1/30
Charles Babbage’s Analytical Engine SimulatorOpen in new tab/window

Code Explanation

To transpose Ada Lovelace’s Note G algorithm into a set of cards/instructions to be processed by the analytical engine the program will first need to loads some values in the store using Number cards (N). (You can check at the end of this post for a full list of instructions that can be processed by the Analytical Engine emulator.)

N1 1
N2 2
N3 4
.Bernoulli numbers shifted by 12 digits
N21 166666666667
N22 -33333333333
N23 23809523809
N24 0

Then the Note G algorithms contains 25 arithmetic operations clearly described on Ada Lovelace’s note provided below. Let’s look at the first operation:

For instance the first operation is a multiplication of variable V2 and V3. V stands for variable, each variable being stored using one column of the store. e.g. V2 refers to the 2nd column of the store. As indicated the result of this operation will be stored three times in column V4, V5 and V6.
This is how this operation would be coded using punched cards:

X     .Load operation card for multiplication
L2    .Load V2 (=2)
L3    .Load V3 (=4)
S4    .Store the result of V2xV3 = 2x4 = 8  in column 4 (V4)
S5    .Store the result in column 5 (V5)
S6    .Store the result in column 6 (V6)

We can now move to the next operation in the algorithm which is a subtraction:

With this operation we are subtracting V1 from V4 and storing the result in V4. (V4 = V4 – V1).This is how this operation would be coded using punched cards:

-     .Load operation card for subtraction
Z4    .Load V4 (=8) (and reset the column to 0)
L1    .Load V3 (=1)
S4    .Store the result of V4-V1 = 8-1 = 7  in column 4 (V4)

We can use this approach to transpose all 25 operations using the relevant punched cards. You can see the result in the emulator and use it to test the Note-G algorithm.

Full Code for Ada Lovelace’s Note G Algorithm:

.Note-G Algorithm
.An algorithm to calculate Bernoulli Number B7 (-1/30)
.Based on Ada Lovelace's Note - G algorithm
N1 1
N2 2
N3 4
.Bernoulli numbers shifted by 12 digits
N21 166666666667 .B1
N22 -33333333333 .B3
N23 23809523809 .B5
N24 0 .B7
.1
X
L2
L3
S4
S5 
S6
.2
-
Z4
L1
S4
.3
+
Z5
L1
S5
.4
/
Z4
<12
Z5
S11'
.5
Z11
L2
S11'
.6
-
Z13
Z11
S13
.7
L3
L1
S10
.8
+
L2
Z7
S7
.9
/
L6
<12
L7
S11'
.10
X
L21
L11
S12
L12
>12
L1
S12
.11
+
Z12
Z13
S13
.12
-
Z10
L1
S10
.13
-
Z6
L1
S6
.14
+
L1
Z7
S7
.15
/
L6
<12
L7
S8'
.16
X
Z8
Z11
S11
L11
>12
L1
S11
.17
-
Z6
L1
S6
.18
+
L1
Z7
S7
.19
/
L6
<12
L7
S9'
.20
X
Z9
Z11
S11
L11
>12
L1
S11
.21
X
L22
L11
S12
L12
>12
L1
S12
.22
+
Z12
Z13
S13
.23
-
Z10
L1
S10
.13 -REPEAT-
-
Z6
L1
S6
.14
+
L1
Z7
S7
.15
/
L6
<12
L7
S8'
.16
X
Z8
Z11
S11
L11
>12
L1
S11
.17
-
Z6
L1
S6
.18
+
L1
Z7
S7
.19
/
L6
<12
L7
S9'
.20
X
Z9
Z11
S11
L11
>12
L1
S11
.21
X
L23
L11
S12
L12
>12
L1
S12
.22
+
Z12
Z13
S13
.23
-
Z10
L1
S10
.24
-
Z24
L13
S24
P
.25
L1
Z3
S3
Z6
Z7
B
H
Charles Babbage’s Analytical Engine SimulatorOpen in new tab/window

Analytical Engine Instruction Set

The table below describes the different instructions/punched cards the analytical engine would have been able to process:

Opcode Instruction Example Description
N Number N1 5 Used to store a given number (e.g. 5) in the store at a specific location (e.g. 1)
L Load L2 Load a value from the store, at a specified location (e.g. 2) to the Mill Ingress axis, leaving the store column unchanged.
Z Load Z2 Load a value from the store, at a specified location/column (e.g. 2) to the Mill Ingress axis, resetting the store column to 0.
S Save S2 Store the value currently in the Mill Egress axis to a given location/column in the Store.
+ Add + Add the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this addition is stored in the Egress Axis.
Subtract Subtract the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this subtraction is stored in the Egress Axis.
x Multiply Multiply the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this multiplication is stored in the Egress Axis.
/ Divide / The value in the first Ingress Axis is divided by the value in the second Ingress Axis. The quotient is placed on the Primed Egress Axis and the remainder on the Egress Axis.
< Step up <6 Step up (left right) by n digits in the Ingress Axis. e.g. <3 to multiply the Ingress value by 1,000.
> Step down >6 Step down (shift right) by n digits in the Ingress Axis. e.g. >3 to divide the Ingress value by 1,000.
CB+ Back Always CB+7 To skip backward (and repeat) a given number of cards in the reader.
CB? Back only if run-up lever is set CB?7 To skip backward (and repeat) a given number of cards in the reader if run-up lever is set.
CF+ Forward Always CF+7 To skip forward a given number of cards in the reader.
CF? Forward only if run-up lever is set CF?7 To skip forward a given number of cards in the reader if run-up lever is set.
P Print P Print the value on the mill axis that the most recent operation most recently modified (e.g. the Mill Egress axis after an arithmetic operation, the Ingress axis after a L instruction, etc.).
B Bell B Ring the bell to get the attention of the engine attendant.
H Halt H Stop the engine. Stop the execution of the program.

Read More…

Check the following two blog posts:

Charles Babbage’s Analytical Engine Emulator

In 19th-century London, Charles Babbage, an English mathematician and inventor, embarked on a groundbreaking quest to build the Analytical Engine, a mechanical precursor to the modern computer. Frustrated by errors in manual calculations, Babbage envisioned a machine capable of performing complex computations through programmable instructions. His collaboration with Ada Lovelace, who wrote the first computer program for the engine, revealed its full potential, laying the foundation for the digital age and establishing Lovelace as the world’s first computer programmer.

The Genesis of the Analytical Engine

Charles Babbage’s journey began with the Difference Engine, a mechanical calculator designed to compute polynomial functions. You can use our online difference engine emulator to find out more about this invention. Babbage’s ambition extended far beyond simple calculations: he envisioned a machine capable of performing any mathematical operations, guided by a set of instructions — a concept we now recognise as programming. This vision culminated in the design of the Analytical Engine.

The Collaboration with Ada Lovelace

Ada Lovelace, the daughter of the poet Lord Byron, is celebrated for her collaboration with Babbage on the Analytical Engine. Lovelace’s deep understanding of the engine’s potential led her to write a series of notes translating and expanding upon an Italian article about the engine. In these notes, she described an algorithm for the engine to compute Bernoulli numbers, which is widely regarded as the first computer program. Her visionary insights into the engine’s capabilities earned her the title of the world’s first computer programmer.

Main Components of the Analytical Engine

The Analytical Engine comprised several key components, each serving a distinct function:

The Mill: This was the computational heart of the engine, responsible for performing arithmetic operations. It was akin to the central processing unit (CPU) in modern computers, executing instructions and manipulating data.

The Store: This component served as the memory of the engine, holding numbers and intermediate results. It was analogous to today’s random-access memory (RAM), storing data that the Mill could retrieve and process. The approach used to store decimal numbers (as opposed to binary numbers in modern computers) using mechanical cog wheels was already a key concept of Charles Babbage’s difference engine.

The Card Reader: The engine was designed to accept input through punched cards, a concept borrowed from the Jacquard loom, a device used in the textile industry: The loom used punched cards to control the weaving of intricate patterns.

The Control Unit: This component directed the sequence of operations, determining which instructions the Mill should execute and when. It was the precursor to the control unit in modern computers, managing the flow of data and instructions.

The PrinterThe result of calculations performed by the Mill was envisioned to be either printed or punched onto cards.

The Analytical Engine Emulator

Despite its revolutionary design, the Analytical Engine was never fully constructed. This is mainy due to the technological limitations and high costs of precision engineering in the 19th century, as well as Babbage’s struggles to secure consistent funding and support for the project.

From the documentation produce by Charles Babbage and Ada Lovelace we can however understand and predict how the machine was intended to operate. The documentation describes the different sets of punched cards (instructions) that the machine had been designed to process. The work of John Walker published on his website (fourmilab), will provide you detailed information about the Analytical Engine and how it operates.

We have recreated here a functioning emulator the Analytical Engine of the to demonstrate how the machine was designed to operate. This emulator include pre-built programs that you can load and test online.
Charles Babbage’s Analytical Engine SimulatorOpen in new tab/window

The Inspiration Behind Punched Cards

Babbage’s idea of using punched cards to program the Analytical Engine was inspired by the Jacquard loom, invented by Joseph Marie Jacquard in 1804. The loom used punched cards to automate the weaving of complex patterns, revolutionising the textile industry. Babbage recognised the potential of this technology for programming his engine, allowing it to perform complex sequences of operations automatically.

The table below describes the different instructions/punched cards the analytical engine would have been able to process:

Opcode Instruction Example Description
N Number N1 5 Used to store a given number (e.g. 5) in the store at a specific location (e.g. 1)
L Load L2 Load a value from the store, at a specified location (e.g. 2) to the Mill Ingress axis, leaving the store column unchanged.
Z Load Z2 Load a value from the store, at a specified location/column (e.g. 2) to the Mill Ingress axis, resetting the store column to 0.
S Save S2 Store the value currently in the Mill Egress axis to a given location/column in the Store.
+ Add + Add the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this addition is stored in the Egress Axis.
Subtract Subtract the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this subtraction is stored in the Egress Axis.
x Multiply Multiply the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this multiplication is stored in the Egress Axis.
/ Divide / The value in the first Ingress Axis is divided by the value in the second Ingress Axis. The quotient is placed on the Primed Egress Axis and the remainder on the Egress Axis.
< Step up <6 Step up (left right) by n digits in the Ingress Axis. e.g. <3 to multiply the Ingress value by 1,000.
> Step down >6 Step down (shift right) by n digits in the Ingress Axis. e.g. >3 to divide the Ingress value by 1,000.
CB+ Back Always CB+7 To skip backward (and repeat) a given number of cards in the reader.
CB? Back only if run-up lever is set CB?7 To skip backward (and repeat) a given number of cards in the reader if run-up lever is set.
CF+ Forward Always CF+7 To skip forward a given number of cards in the reader.
CF? Forward only if run-up lever is set CF?7 To skip forward a given number of cards in the reader if run-up lever is set.
P Print P Print the value on the mill axis that the most recent operation most recently modified (e.g. the Mill Egress axis after an arithmetic operation, the Ingress axis after a L instruction, etc.).
B Bell B Ring the bell to get the attention of the engine attendant.
H Halt H Stop the engine. Stop the execution of the program.

Similarities and Differences with Modern Computers

The Analytical Engine shared several similarities with modern computers:

Programmability: Both can be programmed to perform a wide range of tasks, guided by a set of instructions.
Memory and Processing: The Store and Mill in the Analytical Engine are analogous to memory and CPU in modern computers.
Input/Output: Both use mechanisms for inputting data and outputting results, although the methods differ.

However, there are also significant differences:

Mechanical vs. Electronic: The Analytical Engine was purely mechanical, relying on gears and levers, while modern computers are electronic, using transistors and circuits.
Size and Speed: Modern computers are exponentially faster and more compact than the Analytical Engine, which was never fully constructed due to its complexity and the limitations of 19th-century technology.
Decimal vs. Binary: The Analytical Engine processed decimal numbers, reflecting the mathematical conventions of its time. In contrast, modern computers operate using binary numbers, which are more efficient for electronic computation.

Read More…

Check the following two blog posts:

Creating a Visual Hierarchy in HTML/CSS

In this post, we will explore the concept of visual hierarchy and how you can use your coding skills to recreate a specific visual layout. By the end of this challenge, you will have a better understanding of how to draw the reader’s attention to specific sections of a webpage using HTML and CSS. But first, let’s start with a short experiment. Check the picture below and check if it worked.

Did it work? In other words, did you read the text in the order mentioned on the picture?

Understanding the Concept of Visual Hierarchy

Visual hierarchy is a design principle that guides the viewer’s eye through different elements on a graphic or on a page, emphasising some over others. It is crucial in both print and digital media to ensure that the most important information stands out. For example, on a book cover, the title or the author’s name might be emphasised using larger fonts, bold colours, or strategic placement.

In web design, visual hierarchy helps users navigate and understand the content quickly. By using different sizes, colours, and placements, you can guide the user’s attention to the most critical parts of your webpage.

Coding Challenge: Recreate the Visual Hierarchy

Your task is to recreate the visual hierarchy similar to the one shown in the above image, using HTML and CSS. This layout uses text elements of varying sizes and positions to create a clear hierarchy.

To achieve this layout, you will need to use several CSS properties that control text formatting, positioning, and spacing. Here are some of the main properties you’ll use:

CSS Properties to Format Text:

  • font-family: Changes the font type used for the text. (e.g. Arial, Times New Roman, Verdana, etc.)
  • font-size: Controls the size of the text. Larger sizes draw more attention.
  • font-weight: Makes text bold or normal. Bold text stands out more.
  • font-style: Makes text italic or normal.
  • color: Sets the colour of the text. Contrasting colours can highlight important information.
  • text-align: Aligns text to the left, right, center, or justified.

Positioning and Alignment:

  • position: Allows you to position elements using values like static, relative, absolute, fixed, or sticky.
  • top, bottom, left, right: Used with position to specify the exact placement.
  • display: Controls the display behavior (e.g., block, inline, flex).

Spacing:
To understand the concepts of margin, padding and borders you may want to do some quick research on understanding the “CSS Box Model”.

  • margin: Adds space outside an element, pushing other elements away.
  • padding: Adds space inside an element, increasing the area between the content and the border.
  • border: Adds a border around an element, which can be used to separate or highlight sections.

HTML/CSS Code

Here is a basic example to get you started. You will need to apply more CSS properties to the different elements of the page to create your own visual hierarchy.


unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area